package com.breakfast.fun.ui.home.product;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.breakfast.fun.R;
import com.breakfast.fun.adapter.home.NormalProductAdapter;
import com.breakfast.fun.adapter.home.PopCartAdapter;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.dao.DaoMaster;
import com.breakfast.fun.dao.ProductCartDao;
import com.breakfast.fun.data.entity.home.Product;
import com.breakfast.fun.data.entity.home.ProductClasses;
import com.breakfast.fun.data.entity.home.product.ProductDetail;
import com.breakfast.fun.data.entity.home.product.ProductState;
import com.breakfast.fun.data.entity.home.product.WeekdayState;
import com.breakfast.fun.event.CartEvent;
import com.breakfast.fun.event.PopEvent;
import com.breakfast.fun.ui.user.cart.UserCartActivity;
import com.breakfast.fun.util.DaoUtil;
import com.breakfast.fun.util.DensityUtil;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.PopUtil;
import com.breakfast.fun.util.ScreenUtil;
import com.breakfast.fun.util.T;
import com.breakfast.fun.view.widget.AutoHeightListView;
import com.breakfast.fun.view.widget.BookCountDown;
import com.breakfast.fun.view.widget.CustomDialog;
import com.breakfast.fun.view.widget.CustomGridView;
import com.breakfast.fun.view.widget.HorizontalScrollViewListener;
import com.breakfast.fun.view.widget.ObservableHorizontalScrollView;
import com.breakfast.fun.view.widget.ObservableScrollView;
import com.breakfast.fun.view.widget.ScrollViewListener;
import com.breakfast.fun.view.widget.TitleBarView;
import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;

public class NormalProductActivity extends BaseActivity<NormalProductPresenter, NormalProductModel> implements NormalProductContract.View {

    @Bind(R.id.tbv_product)
    TitleBarView tbvProduct;
    @Bind(R.id.iv_product_top)
    ImageView ivProductTop;
    @Bind(R.id.bcd_product)
    BookCountDown bcdProduct;
    @Bind(R.id.tv_product_sell_count)
    TextView tvProductSellCount;
    @Bind(R.id.rg_send_time)
    RadioGroup rgSendTime;
    @Bind(R.id.cgv_product)
    CustomGridView cgvProduct;
    @Bind(R.id.v_product_line)
    View vProductLine;
    @Bind(R.id.rl_product_bottom)
    RelativeLayout rlProductBottom;
    @Bind(R.id.tv_product_total_num)
    TextView tvProductTotalNum;
    @Bind(R.id.tv_produtc_total)
    TextView tvProdutcTotal;
    @Bind(R.id.tv_product_total_price)
    TextView tvProductTotalPrice;
    @Bind(R.id.btn_product_submit)
    Button btnProductSubmit;
    @Bind(R.id.rl_cart_bottom)
    RelativeLayout rlCartBottom;
    @Bind(R.id.ll_cart_content)
    LinearLayout llCartContent;
    @Bind(R.id.ll_product_top_date)
    LinearLayout llProductTopDate;
    @Bind(R.id.ll_product_date)
    LinearLayout llProductDate;
    @Bind(R.id.hsv_normal_product)
    ObservableHorizontalScrollView mHsvNormalProduct;
    @Bind(R.id.hsv_normal_product_top)
    ObservableHorizontalScrollView mHsvNormalProductTop;
    @Bind(R.id.rg_send_top_time)
    RadioGroup rgSendTopTime;
    @Bind(R.id.rl_normal_product_bookCountDown)
    RelativeLayout rlNormalProductBookCountDown;
    @Bind(R.id.sv_product)
    ObservableScrollView svProduct;
    @Bind(R.id.iv_cart_normal)
    ImageView ivCartNormal;
    @Bind(R.id.rl_normal_product)
    RelativeLayout rlNormalProduct;

    private String spiltDate = new Date().getYear() + 1900 + "-";
    public static String chooseDate = "";
    public static int earliestDate;             //最近可用日期在list中的index
    public static int curPosition;

    private String[] weekList = {"", "周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    private List<RadioButton> rbSendTopTimeList = new ArrayList<RadioButton>();
    private List<RadioButton> rbSendTimeList = new ArrayList<RadioButton>();


    private List<WeekdayState> weekdayStates;

    private NormalProductAdapter adapter;

    private List<Product> dataList = new ArrayList<>();

    private ProductClasses productClasses;

    private PopupWindow popupWindow;

    private ProductCartDao mProductCartDao;

    @Override
    public int getLayoutId() {
        return R.layout.activity_normal_product;
    }

    @Override
    public void initView() {


        EventBus.getDefault().register(this);
        productClasses = (ProductClasses) getIntent().getSerializableExtra("product");
        L.d("product---" + productClasses);
        mProductCartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();
        tbvProduct.setTitleNoRight(productClasses.getClassName());
        tbvProduct.setBack(this);

        tvProductSellCount.setText(productClasses.getSellcount() + "");

        Glide.with(context)
                .load(productClasses.getDetailImage())
                .placeholder(R.drawable.bg_cache_banner)
                .error(R.drawable.bg_cache_banner)
                .crossFade()
                .into(ivProductTop);

        initBookCountDown(productClasses.getClosetime());

        btnProductSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ((tvProductTotalNum.getVisibility() != View.VISIBLE)
                        || tvProductTotalNum.getText().equals("0")) {
                    T.show("购物车为空,请添加商品");
                    return;
                }
                Intent intent = new Intent(NormalProductActivity.this, UserCartActivity.class);
                startActivity(intent);
            }
        });

        //点击购物车弹出PopWindow
        rlCartBottom.setOnClickListener(v -> {
            if (DaoUtil.getProductCartDao().loadAll().size() == 0) {
                return;
            }

            View contentView = LayoutInflater.from(NormalProductActivity.this).inflate(R.layout.widget_pop_cart, null);

            popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
            PopUtil.setPop(popupWindow);
            //设置底部弹出，间距48dp
            //如果有虚拟按键，则弹出的高度加上虚拟按键的高度
            int y = 0;
            if (ScreenUtil.hasNavBar(context)) {
                y = DensityUtil.dp2px(context, 48) + ScreenUtil.getBottomStatusHeight(context);
            } else {
                y = DensityUtil.dp2px(context, 48);
            }
            if (!popupWindow.isShowing()) {
                popupWindow.showAtLocation(NormalProductActivity.this.findViewById(R.id.rl_product_bottom),
                        Gravity.BOTTOM, 0, y);
            }
            PopUtil popUtil = new PopUtil();
            popUtil.backgroundAlpha(NormalProductActivity.this, 0.5f);

            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    adapter.refreshCartParam();
                    adapter.notifyDataSetChanged();
                    popUtil.backgroundAlpha(NormalProductActivity.this, 1f);
                }
            });


            LinearLayout llPopCartClear = (LinearLayout) contentView.findViewById(R.id.ll_pop_cart_clear);

            AutoHeightListView ahlvPopCart = (AutoHeightListView) contentView.findViewById(R.id.ahlv_pop_cart);
            PopCartAdapter mAdapter = new PopCartAdapter(context, DaoUtil.getProductCartDao().loadAll());
            ahlvPopCart.setAdapter(mAdapter);

            llPopCartClear.setOnClickListener(v1 -> {
                mDialog = new CustomDialog(NormalProductActivity.this, R.style.dialog_style,
                        R.layout.dialog_custom, "提示", "确定要清空购物车吗？", false, false, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mDialog.dismiss();
                        popupWindow.dismiss();
                        mProductCartDao.deleteAll();
                        EventBus.getDefault().post(new CartEvent(0, 0));
                        mProductCartDao = DaoUtil.getProductCartDao();
                        PopCartAdapter popCartAdapter = new PopCartAdapter(context, mProductCartDao.loadAll());
                        ahlvPopCart.setAdapter(popCartAdapter);
                        adapter.refreshCartParam();
                        adapter.notifyDataSetChanged();
                    }
                });
                mDialog.show();
            });


        });

        svProduct.setScrollViewListener(new ScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                //选择日期顶部悬浮
                //状态切换时同步滚动位置
                if (y >= rlNormalProductBookCountDown.getHeight() + ivProductTop.getHeight()) {
                    llProductTopDate.setVisibility(View.VISIBLE);
                    rbSendTopTimeList.get(curPosition).setChecked(true);
                } else {
                    llProductTopDate.setVisibility(View.GONE);
                    rbSendTimeList.get(curPosition).setChecked(true);
                }
                chooseDate = weekdayStates.get(curPosition).getWdate();

            }
        });


        mHsvNormalProduct.setScrollViewListener(new HorizontalScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldx, int oldy) {
                mHsvNormalProductTop.scrollTo(x, 0);
            }
        });

        mHsvNormalProductTop.setScrollViewListener(new HorizontalScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldx, int oldy) {
                mHsvNormalProduct.scrollTo(x, 0);
            }
        });

    }

    private void initBookCountDown(String closeTime) {
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            Long now = System.currentTimeMillis();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DATE);
            String dates = year + "-" + (month < 10 ? "0" + month : month)
                    + "-" + (day < 10 ? "0" + day : day) + " " + closeTime;
            Date date = df.parse(dates);
            if (date.getTime() < now) {
                bcdProduct.setTime(0, 0, 0, true);
                return;
            }
            Long diff = date.getTime() - now;
            Long days = diff / (1000 * 60 * 60 * 24);
            Long hours = (diff - days * (1000 * 60 * 60 * 24))
                    / (1000 * 60 * 60);
            Long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours
                    * (1000 * 60 * 60))
                    / (1000 * 60);
            Long second = (diff - days * (1000 * 60 * 60 * 24) - hours
                    * (1000 * 60 * 60) - minutes * (1000 * 60)) / (1000);

            bcdProduct.setTime(hours.intValue(), minutes.intValue(),
                    second.intValue(), true);

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showProductState(ProductState productState) {
        weekdayStates = productState.getData();
        int i = 0;
        while (i < weekdayStates.size()) {
            RadioButton radioButton = (RadioButton) LayoutInflater.from(context).inflate(R.layout.product_time_radio_button, null);
            addRadioButton(rgSendTime, radioButton, i);
            rbSendTimeList.add(radioButton);
            analyseWeek(radioButton, i);
            i++;
        }
        i = 0;
        while (i < weekdayStates.size()) {
            RadioButton radioButton = (RadioButton) LayoutInflater.from(context).inflate(R.layout.product_time_radio_button, null);
            addRadioButton(rgSendTopTime, radioButton, i);
            rbSendTopTimeList.add(radioButton);
            analyseWeek(radioButton, i);
            i++;
        }

        //获取最近的可用日期
        for (int j = 0; j < productState.getData().size(); j++) {
            if (productState.getData().get(j).getState().equals("2")) {
                earliestDate = j;
                break;
            }
        }

        L.d("classId------" + productClasses.getClassId());
        presenter.getProductDetail(productClasses.getClassId() + "");

        //已经打烊，选择日期不可点击
        if (bcdProduct.getTimeIsComplete()) {
//            setRadioButtonFalse(earliestDate);
//            rbSendTimeList.get(curPosition).setChecked(false);
            setTimeDisableClick(rbSendTimeList.get(curPosition));
            setTimeDisableClick(rbSendTopTimeList.get(curPosition));
//            rbSendTimeList.get(curPosition).setEnabled(false);
            rbSendTimeList.get(curPosition + 1).setChecked(true);
            rbSendTopTimeList.get(curPosition + 1).setChecked(true);
            curPosition = curPosition + 1;
            chooseDate = weekdayStates.get(earliestDate + 1).getWdate();
        }

    }

    public void addRadioButton(RadioGroup radioGroup, RadioButton rb, int id) {
        Drawable drawable = getResources().getDrawable(R.drawable.selector_time);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        rb.setCompoundDrawables(null, null, null, drawable);
        rb.setCompoundDrawablePadding(DensityUtil.dp2px(context, 3));
        rb.setTextColor(getResources().getColor(R.color.black_deep));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) ((ScreenUtil.getScreenWidth(context) - 20) / 4.5), ViewGroup.LayoutParams.WRAP_CONTENT);
        rb.setLayoutParams(params);
        rb.setId(id);
        radioGroup.addView(rb);
    }

    @Override
    public void showProductDetail(ProductDetail productDetail) {
        dataList = productDetail.getData();
        adapter = new NormalProductAdapter(context, dataList);
        cgvProduct.setAdapter(adapter);
        adapter.setAddClickListener(new NormalProductAdapter.addClickListener() {
            @Override
            public void add(View view) {
                mCartAnimUtil.setFromView(view);
                mCartAnimUtil.setRootView(rlNormalProduct);
                mCartAnimUtil.setToView(ivCartNormal);
                mCartAnimUtil.startAnim();
            }
        });


    }


    /**
     * 设置 不可选中
     *
     * @param rb_time
     */
    private void setTimeDisableClick(RadioButton rb_time) {
        rb_time.setEnabled(false);
        Drawable drawable = getResources().getDrawable(R.drawable.ic_product_expired);
        // / 这一步必须要做,否则不会显示.
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        rb_time.setCompoundDrawables(null, null, null, drawable);
        rb_time.setCompoundDrawablePadding(DensityUtil.dp2px(context, 3));
    }

    private void analyseWeek(RadioButton rb_time, int positon) {

        if (weekdayStates.size() > positon) {
            // 设置日期
            rb_time.setTag(positon);
            rb_time.setText(weekList[weekdayStates.get(positon).getWday()]
                    + "\n"
                    + weekdayStates.get(positon).getWdate()
                    .replaceAll(spiltDate, ""));
            if (weekdayStates.get(positon).getState().equals("1")) {// 不可选
                setTimeDisableClick(rb_time);
            } else if (weekdayStates.get(positon).getState().equals("2")) {// 选中
                rb_time.setChecked(true);
                //当前被选中的Position
                curPosition = positon;
                // 设置选中的日期
                chooseDate = weekdayStates.get(positon).getWdate();
            } else if (weekdayStates.get(positon).getState().equals("3")) {// 可选
            } else {

            }
            rb_time.setVisibility(View.VISIBLE);
        } else {
            rb_time.setVisibility(View.INVISIBLE);
        }

        rb_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseDate = weekdayStates.get(positon).getWdate();
                adapter.notifyDataSetChanged();
                curPosition = positon;

            }
        });
    }

    //设置所有日期选择不可点击
    private void setRadioButtonFalse(int j) {
        rbSendTimeList.get(j).setEnabled(false);
        setTimeDisableClick(rbSendTimeList.get(j));
        rbSendTopTimeList.get(j).setEnabled(false);
        setTimeDisableClick(rbSendTopTimeList.get(j));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CartEvent event) {
        if (event.getTotalNum() > 0) {
            tvProductTotalNum.setVisibility(View.VISIBLE);
        } else {
            tvProductTotalNum.setVisibility(View.GONE);
        }
        tvProductTotalNum.setText(event.getTotalNum() + "");
        if (event.getTotalPrice() < 0) {
            event.setTotalPrice(0);
        }
        tvProductTotalPrice.setText(String.format("%.2f", event.getTotalPrice()));

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(PopEvent event) {
        if (event.getClassName().equals(NormalProductActivity.class.getSimpleName())) {
            popupWindow.dismiss();
        }
    }

    @Override
    protected void destroyView() {
        super.destroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter = new NormalProductAdapter(context, dataList);
        cgvProduct.setAdapter(adapter);
        adapter.setAddClickListener(new NormalProductAdapter.addClickListener() {
            @Override
            public void add(View view) {
                mCartAnimUtil.setFromView(view);
                mCartAnimUtil.setRootView(rlNormalProduct);
                mCartAnimUtil.setToView(ivCartNormal);
                mCartAnimUtil.startAnim();
            }
        });
    }

    @Override
    public void onLowMemory() {
        // TODO Auto-generated method stub
        if (mCartAnimUtil != null) {
            try {
                //移除添加购物车中多创建的ImageView
                mCartAnimUtil.getRootView().removeAllViews();
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.onLowMemory();
        }
    }
}
